﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32;

namespace MDM.GUI.MDM.Business
{
    class ActionManager
    {

        public static void DoRegistry(MDM.DataObjects.Registry RegistryItem)
        {

            if (RegistryItem.Type == "Import")
            {
                string strKey = RegistryItem.Key;
                strKey = strKey.Replace("[", "");
                strKey = strKey.Replace("]", "");
                Microsoft.Win32.Registry.SetValue(strKey, RegistryItem.Name, RegistryItem.Value);
            }

            if (RegistryItem.Type == "Delete")
            {
                //   Microsoft.Win32.Registry.
                string strKey = RegistryItem.Key;
                strKey = strKey.Replace("[", "");
                strKey = strKey.Replace("]", "");

                /*          RegistryKey ClassesRoot = Microsoft.Win32.Registry.ClassesRoot;
                          RegistryKey CurrentConfig = Microsoft.Win32.Registry.CurrentConfig;
                          RegistryKey CurrentUser = Microsoft.Win32.Registry.CurrentUser;
                          RegistryKey DynData = Microsoft.Win32.Registry.DynData;
                          RegistryKey LocalMachine = Microsoft.Win32.Registry.LocalMachine;
                          RegistryKey PerformanceData = Microsoft.Win32.Registry.PerformanceData;
                          RegistryKey Users = Microsoft.Win32.Registry.Users;            */

                RegistryKey key = null;
                if (strKey.IndexOf(Microsoft.Win32.Registry.CurrentUser.Name) == 0)
                {
                    key = Microsoft.Win32.Registry.CurrentUser;
                }


                if (strKey.IndexOf(Microsoft.Win32.Registry.ClassesRoot.Name) == 0)
                {
                    key = Microsoft.Win32.Registry.ClassesRoot;
                }


                if (strKey.IndexOf(Microsoft.Win32.Registry.CurrentConfig.Name) == 0)
                {
                    key = Microsoft.Win32.Registry.CurrentConfig;
                }
                /*
                if (strKey.IndexOf(Microsoft.Win32.Registry.DynData.Name) == 0)
                {
                    key = Microsoft.Win32.Registry.DynData;
                }
                */

                if (strKey.IndexOf(Microsoft.Win32.Registry.LocalMachine.Name) == 0)
                {
                    key = Microsoft.Win32.Registry.LocalMachine;
                }


                if (strKey.IndexOf(Microsoft.Win32.Registry.PerformanceData.Name) == 0)
                {
                    key = Microsoft.Win32.Registry.PerformanceData;
                }


                if (strKey.IndexOf(Microsoft.Win32.Registry.Users.Name) == 0)
                {
                    key = Microsoft.Win32.Registry.Users;
                }


                if (key != null)
                {
                    //strKey = strKey.Replace(key.Name, "");
                    //strKey = strKey.Remove(0, 1);
                    /*   for (int i = 0; i < strKey.Length; i++)
                       {
                           if (strKey[i]=="\")
                           {
                            
                           }
                       }*/
                    String s1 = @"Software\ATU";
                    RegistryKey key1 = key.OpenSubKey(s1, true);
                    key1.DeleteValue(RegistryItem.Name);
                    key1.Close();
                }



            }
            // key.DeleteValue("temp_key=kdkJKH#KK#L");




        }




        public static void DoDos(MDM.DataObjects.Dos DosItem)
        {
            Process.Start("cmd", "/c " + DosItem.Command);
        }




        public static void DoService(MDM.DataObjects.Service item)
        {
            InstallService(item.File, "oanhoanh", "oanh");


        }

        #region Private Variables
   /*     private string _servicePath;
        private string _serviceName;
        private string _serviceDisplayName;*/
        #endregion Private Variables
        #region DLLImport
        [DllImport("advapi32.dll")]
        public static extern IntPtr OpenSCManager(string lpMachineName, string lpSCDB, int scParameter);
        [DllImport("Advapi32.dll")]
        public static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName,
        int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName,
        string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);
        [DllImport("advapi32.dll")]
        public static extern void CloseServiceHandle(IntPtr SCHANDLE);
        [DllImport("advapi32.dll")]
        public static extern int StartService(IntPtr SVHANDLE, int dwNumServiceArgs, string lpServiceArgVectors);
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern IntPtr OpenService(IntPtr SCHANDLE, string lpSvcName, int dwNumServiceArgs);
        [DllImport("advapi32.dll")]
        public static extern int DeleteService(IntPtr SVHANDLE);
        [DllImport("kernel32.dll")]
        public static extern int GetLastError();
        #endregion DLLImport

        public static bool InstallService(string svcPath, string svcName, string svcDispName)
        {
            #region Constants declaration.
            int SC_MANAGER_CREATE_SERVICE = 0x0002;
            int SERVICE_WIN32_OWN_PROCESS = 0x00000010;
            //int SERVICE_DEMAND_START = 0x00000003;
            int SERVICE_ERROR_NORMAL = 0x00000001;
            int STANDARD_RIGHTS_REQUIRED = 0xF0000;
            int SERVICE_QUERY_CONFIG = 0x0001;
            int SERVICE_CHANGE_CONFIG = 0x0002;
            int SERVICE_QUERY_STATUS = 0x0004;
            int SERVICE_ENUMERATE_DEPENDENTS = 0x0008;
            int SERVICE_START = 0x0010;
            int SERVICE_STOP = 0x0020;
            int SERVICE_PAUSE_CONTINUE = 0x0040;
            int SERVICE_INTERROGATE = 0x0080;
            int SERVICE_USER_DEFINED_CONTROL = 0x0100;
            int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED |
            SERVICE_QUERY_CONFIG |
            SERVICE_CHANGE_CONFIG |
            SERVICE_QUERY_STATUS |
            SERVICE_ENUMERATE_DEPENDENTS |
            SERVICE_START |
            SERVICE_STOP |
            SERVICE_PAUSE_CONTINUE |
            SERVICE_INTERROGATE |
            SERVICE_USER_DEFINED_CONTROL);
            int SERVICE_AUTO_START = 0x00000002;
            #endregion Constants declaration.
            try
            {
                IntPtr sc_handle = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
                if (sc_handle.ToInt32() != 0)
                {
                    IntPtr sv_handle = CreateService(sc_handle, svcName, svcDispName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, svcPath, null, 0, null, null, null);
                    if (sv_handle.ToInt32() == 0)
                    {
                        CloseServiceHandle(sc_handle);
                        return false;
                    }
                    else
                    {
                        //now trying to start the service
                        int i = StartService(sv_handle, 0, null);
                        // If the value i is zero, then there was an error starting the service.
                        // note: error may arise if the service is already running or some other problem.
                        if (i == 0)
                        {
                            //Console.WriteLine("Couldnt start service");
                            return false;
                        }
                        //Console.WriteLine("Success");
                        CloseServiceHandle(sc_handle);
                        return true;
                    }
                }
                else
                    //Console.WriteLine("SCM not opened successfully");
                    return false;
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /*      [RunInstaller(true)]
              public class MyProjectInstaller : Installer
              {
                  private ServiceInstaller serviceInstaller1;
                  private ServiceProcessInstaller processInstaller;

                  public MyProjectInstaller()
                  {
                      // Instantiate installers for process and services.
                      processInstaller = new ServiceProcessInstaller();
                      serviceInstaller1 = new ServiceInstaller();

                      // The services run under the system account.
                      processInstaller.Account = ServiceAccount.LocalSystem;

                      // The services are started manually.
                      serviceInstaller1.StartType = ServiceStartMode.Automatic;

                      // ServiceName must equal those on ServiceBase derived classes.
                      serviceInstaller1.ServiceName = "Hello-World Service 1";


                      // Add installers to collection. Order is not important.
                      Installers.Add(serviceInstaller1);
                      Installers.Add(processInstaller);
                  }



              }

              */

        public static void DoWindow(MDM.DataObjects.Window WindowItem)
        {
            //Process.Start("cmd","/c"+WindowItem.Type);

            if (WindowItem.Type == "Execute")
            {
                Process.Start("cmd", "/c " + WindowItem.Path);
            }




            if (WindowItem.Type == "Copy")
            {
                Process.Start("cmd", "/c " + "copy " + WindowItem.Source + " " + WindowItem.Destination);
            }


            if (WindowItem.Type == "Move")
            {
                Process.Start("cmd", "/c " + "move " + WindowItem.Source + " " + WindowItem.Destination);
            }



            if (WindowItem.Type == "Delete")
            {
                Process.Start("cmd", "/c " + "del " + WindowItem.Source);
            }


            if (WindowItem.Type == "Rename")
            {
                Process.Start("cmd", "/c " + "ren " + WindowItem.Source + " " + WindowItem.Destination);
            }



        }





        public static void DoShutdown()
        {
            System.Management.
            ManagementBaseObject mboShutdown = null;
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
            mcWin32.Get();

            // You can't shutdown without security privileges
            mcWin32.Scope.Options.EnablePrivileges = true;
            ManagementBaseObject mboShutdownParams =
                     mcWin32.GetMethodParameters("Win32Shutdown");

            // Flag 1 means we want to shut down the system. Use "2" to reboot.
            mboShutdownParams["Flags"] = "1";
            mboShutdownParams["Reserved"] = "0";
            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutdown = manObj.InvokeMethod("Win32Shutdown",
                                               mboShutdownParams, null);
            }


        }





        public static void DoRestart()
        {
            ManagementBaseObject mboShutdown = null;
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
            mcWin32.Get();

            // You can't shutdown without security privileges
            mcWin32.Scope.Options.EnablePrivileges = true;
            ManagementBaseObject mboShutdownParams =
                     mcWin32.GetMethodParameters("Win32Shutdown");

            // Flag 1 means we want to shut down the system. Use "2" to reboot.
            mboShutdownParams["Flags"] = "2";
            mboShutdownParams["Reserved"] = "0";
            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutdown = manObj.InvokeMethod("Win32Shutdown",
                                               mboShutdownParams, null);
            }

        }

    }
}
